﻿#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <stdlib.h>
#include <string>
#include <vector>
#include <algorithm>
#include <queue>
#include <stack>
#include <unordered_map>
#include <unordered_set>
#include <numeric>
typedef long long ll;

using namespace std;
struct TreeNode {
	int val;
	TreeNode *left;
	TreeNode *right;
	TreeNode(int x) : val(x), left(NULL), right(NULL) {}
	
};
class Node {
public:
	int val;
	Node* left;
	Node* right;
	Node* next;

	Node() : val(0), left(NULL), right(NULL), next(NULL) {}

	Node(int _val) : val(_val), left(NULL), right(NULL), next(NULL) {}

	Node(int _val, Node* _left, Node* _right, Node* _next)
		: val(_val), left(_left), right(_right), next(_next) {}
};
struct ListNode {
	int val;
	ListNode *next;
	ListNode() : val(0), next(nullptr) {}
	ListNode(int x) : val(x), next(nullptr) {}
	ListNode(int x, ListNode *next) : val(x), next(next) {}
};

class Solution {
public:
	int maxProfit(int k, vector<int>& prices) {
		if (prices.size() <= 1)
			return 0;
		int n = prices.size();
		vector<vector<int>> buy(n, vector<int>(k + 1, 0));	//dp[i][j]为在下标i价格时已经买了j支股票的最大利润
		vector<vector<int>> sell(n, vector<int>(k + 1, 0));
		buy[0][0] = -prices[0];
		sell[0][0] = 0;
		for (int i = 1; i <= k; ++i) {
			buy[0][i] = sell[0][i] = INT_MIN / 2;
		}
		for (int i = 1; i < n; i++) {
			buy[i][0] = max(buy[i - 1][0], sell[i - 1][0] - prices[i]);
			for (int j = 1; j <= k; j++) {
				buy[i][j] = max(buy[i - 1][j], sell[i - 1][j] - prices[i]);
				sell[i][j] = max(sell[i - 1][j], buy[i - 1][j - 1] + prices[i]);
			}
		}
		int ans = 0;
		for (int i = 1; i <= k; i++) {
			ans = max(ans, sell[n - 1][i]);
		}
		return ans;
	}
};


int main()
{
	Solution sol;
	ListNode d(4);
	ListNode c(3, &d);
	ListNode b(2, &c);
	ListNode a(1, &b);
	vector<int> t = { 1,2,4,2,5,7,2,4,9,0 };
	vector<int> t2 = { 5,3,1,4,2 };
	vector<vector<int>> test = {{1, 3}, {2, 4}, {10, 11}, {10, 12}, {8, 9}};
	//string test = "anagram";
	string test2 = "nagaram";
	sol.maxProfit(2, t);
	cout <<endl;
}
